package dwrealtime;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
//import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/*import org.json.JSONArray; 
import org.json.JSONStringer;
import org.json.JSONTokener;*/

//import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

public class Dwrealtime extends HttpServlet 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//URLָ��Ҫ���ʵ���ݿ���
//	private static final String URL="jdbc:mysql://localhost:3306/dwaccessDB";
	private static final String URL="jdbc:mysql://localhost:3306/dwjava";
	//MySQL����ʱ���û���
    private static final String NAME="root";
  //MySQL����ʱ������
	private static final String PASSWORD="root";

	/**
	 * Constructor of the object.
	 */
	public Dwrealtime() 
	{
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() 
	{
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
//		System.out.println("detect.query-string " + request.getQueryString());		
		String device_id = request.getParameter("device_id");
        String ip = request.getParameter("ip");
        String portstr = request.getParameter("port");
        String timestr = request.getParameter("time");
        if(device_id==null || device_id=="" || ip==null || ip=="" || portstr==null || portstr=="" || timestr==null || timestr=="")
		{
			return;
		}
		try 
		{
			if(!timehandle(response,timestr,device_id))
			{
				return;
			}
			
		} catch (ParseException e1) 
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try 
		{
			devicehandle(response,ip,portstr,timestr,device_id);
		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*		System.out.println("dwrealtime.detect.query-string " + request.getQueryString());
		String device_id = request.getParameter("device_id");
        String ip = request.getParameter("ip");
        String portstr = request.getParameter("port");
        String timestr = request.getParameter("time");
        System.out.println("dwrealtime...device_id:"+device_id+" ip:"+ip+" port:"+portstr+" time:"+timestr);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();*/
	}
	
	private void devicehandle(HttpServletResponse response,String ip,String portstr,String timestr,String device_id) 
		throws SQLException, IOException
	{
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Connection conn = null;
//			try 
//			{
			conn = DriverManager.getConnection(URL, NAME, PASSWORD);
/*		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		//3.Í¨¹ýÊý¾Ý¿âµÄÁ¬½Ó²Ù×÷Êý¾Ý¿â£¬ÊµÏÖÔöÉ¾¸Ä²é
		Statement stmt = null;
		Statement stmt1 = null;
//			try 
//			{
		stmt = conn.createStatement();
/*		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		ResultSet rs = null;
//			try 
//			{
		String sqlstr = "SELECT COUNT(*) FROM gatesetting WHERE controlerNum = \""+device_id+"\";";	
		rs = stmt.executeQuery(sqlstr);
	//		
/*		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//Ñ¡Ôñimport java.sql.ResultSet;
		try 
		{*/
		int count = 0;
		while(rs.next())
		{//Èç¹û¶ÔÏóÖÐÓÐÊý¾Ý£¬¾Í»áÑ­»·´òÓ¡³öÀ´
			count = rs.getInt(1);
//				System.out.println(rs.getString("controlerNum")+","+rs.getInt("cardnum"));
//				System.out.println(rs.getString("controlerNum")+","+rs.getString("cardnum"));
		}
//			System.out.println("count: "+count);
		rs.close();
		if(stmt!=null) stmt.close();
/*		} catch (SQLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1 = new Date();
		String nowtime = df.format(d1);
		int i=0;
		if(count!=0)
		{
			sqlstr = "UPDATE gatesetting SET stat= 'online',lasttime='"+nowtime+"',IP='"+ip+"',PORT='"+portstr+"' WHERE controlerNum = '"+device_id+"';";			
			stmt1 = conn.createStatement();
			int executeUpdate = stmt1.executeUpdate(sqlstr);
			if(stmt1!=null) stmt1.close();
		}else
		{			
			for(i=0;i<4;i++)
			{
				sqlstr="INSERT INTO gatesetting(controlerNum,IP,PORT,stat,lasttime,gatenum) VALUES('"+device_id+"','"+ip+"','"+portstr+"','online','"+nowtime+"','"+i+"');";
				stmt1 = conn.createStatement();
				int executeUpdate = stmt1.executeUpdate(sqlstr);
				if(stmt1!=null) stmt1.close();
			}
		}
		stmt = conn.createStatement();		
		sqlstr="SELECT cmdstr FROM cmdform WHERE (controlerNum =\"0\" OR controlerNum = \""+device_id+"\");";
		rs = stmt.executeQuery(sqlstr);
		String returnstr="[";
        i=0;	
		while(rs.next() && i<200)
		{			
			returnstr += rs.getString(1)+",";
			i++;
		}
		if(i==0)
		{
			returnstr += "]";
		}else
		{
			StringBuffer buf = new StringBuffer();
			buf.append(returnstr);
			buf.replace(buf.length() - 1, buf.length(), "]");
			returnstr=buf.toString();			
		}
		rs.close();
		if(stmt!=null) stmt.close();
		if(conn!=null) conn.close();
		respondsreturn(response,returnstr);
	}
	
	private boolean timehandle(HttpServletResponse response,String timestr,String device_id) throws ParseException, IOException
	{
//			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DateFormat nowt = new SimpleDateFormat("yyyyMMddHHmmss");
		Date d1 = new Date();
		String nowtime = nowt.format(d1);
	    Date d2 = nowt.parse(timestr);   
	    long diff = Math.abs(d1.getTime() - d2.getTime());
//		    System.out.println("nowtime: "+nowtime+" d1: "+d1.getTime()+" d2: "+d2.getTime()+" diff:"+diff);
		if(diff>180*1000)
		{
			String returnstr = "{\"device_id\":\""+device_id+"\",\"time\":\""+nowtime+"\",\"cmd_code\":\"KQ_TIME\"}";
			respondsreturn(response,returnstr);
			return false;
		}
		return true;
	}
	
	private void respondsreturn(HttpServletResponse response,String returnstr) throws IOException
	{		
		PrintWriter out = response.getWriter();
		out.print(returnstr);
		out.flush();
		out.close();
		return;
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		System.out.println("out: "+request.getContentType());
		if(request.getContentType().contains("multipart/form-data"))
		{
			try 
			{
				multiparthandle(request,response);
			} catch (SQLException | JSONException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(request.getContentType().contains("resultJson"))
		{
			try 
			{
				cmdresulthandle(request,response);
			} catch (SQLException | JSONException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void cmdresulthandle(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException,JSONException
	{
		char[] buf = new char[512];  
        int len = 0;  
        StringBuffer contentBuffer = new StringBuffer(); 
        while ((len = request.getReader().read(buf)) != -1) 
        {  
            contentBuffer.append(buf, 0, len);  
        } 
        String content = contentBuffer.toString();  
        if(content == null)
        {  
            content = "";  
        } 
//        System.out.println("out1: "+ content);
        JSONObject jsonobject = null;
        JSONArray jsonArray = null;
        jsonArray = new JSONArray(content);
//        String device_id=null;
        String trans_id=null;
        String cmd_result=null;
//        String detime=null;
        Connection conn = null;
		conn = DriverManager.getConnection(URL, NAME, PASSWORD);
        for(int i=0 ; i < jsonArray.length() ;i++)
    	{
    	    jsonobject = jsonArray.getJSONObject(i);
//    	    device_id=jsonobject.getString("device_id");
    	    trans_id=jsonobject.getString("trans_id");
    	    cmd_result=jsonobject.getString("cmd_result");
//    	    detime=jsonobject.getString("time");
//    	    System.out.println("device_id:"+device_id+" trans_id:"+trans_id+" cmd_result:"+cmd_result+" time:"+detime);
    	    if(trans_id==null || cmd_result.equals("ERROR"))
		   {		       		
	            return;
		    }else if(cmd_result.equals("OK"))
	        {
		    	try 
				{
					Class.forName("com.mysql.jdbc.Driver");
				} catch (ClassNotFoundException e) 
				{
					System.out.println("com.mysql.jdbc.Driver Exception,109");
				}				
				Statement stmt = null;
				stmt = conn.createStatement();
				String sqlstr=null;
				sqlstr="DELETE FROM cmdform WHERE transid = \""+trans_id+"\";";
				int udresult  = stmt.executeUpdate(sqlstr);
				if(stmt!=null) stmt.close();
	        }
    	}
        if(conn!=null) conn.close();
	}
	
	private void multiparthandle(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException,JSONException
	{		
	//	System.out.println("out.relatime...: "+request.getContentType());
	//	System.out.println("out1: "+request.getParameter());
	//	BufferedReader reader = request.getReader();
	/*		char[] buf = new char[512];  
	    int len = 0;  
	    StringBuffer contentBuffer = new StringBuffer(); 
	    while ((len = request.getReader().read(buf)) != -1) 
	    {  
	        contentBuffer.append(buf, 0, len);  
	    } 
	    String content = contentBuffer.toString();  
	    if(content == null)
	    {  
	        content = "";  
	    } 
	    System.out.println("outrelatime...: "+ content);
	*/        
	    // Check that we have a file upload request
	//    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	 // Create a factory for disk-based file items
	    DiskFileItemFactory factory = new DiskFileItemFactory();
	
	    // Configure a repository (to ensure a secure temp location is used)
	//    ServletContext servletContext = this.getServletConfig().getServletContext();
	//    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	//    factory.setRepository(repository);
	
	    // Create a new file upload handler
	    ServletFileUpload upload = new ServletFileUpload(factory);
	    
	    // Set factory constraints
	    factory.setSizeThreshold(2048);
	    
	//    String tempPath = "/dw/pics"; 
	//    String tempPath = "pics";
	    String tempPath = "/code/server/java/dwserver/dw/WebRoot/tmp";
	/*        System.out.println("dwrealtime..tempPath: "+tempPath);
	    String tempPath1 = request.getRequestURI();
	    System.out.println("dwrealtime..tempPath1: "+tempPath1);
	    String tempPath2 = request.getServletPath();
	    System.out.println("dwrealtime..tempPath2: "+tempPath2);
	    String tempPath3 = request.getSession().getServletContext().getRealPath("/");
	    System.out.println("dwrealtime..tempPath3: "+tempPath3);
	//    String tempPath4 = servletConfig.getServletContext().getRealPath("/");*/
	    
	    File fp1 =new File(tempPath);  
	    if(!fp1.exists())  
	    fp1.mkdirs();  
	    File tempFile = new File(tempPath);
	    factory.setRepository(tempFile);
	//    System.out.println("out.dwrealtime..tempPath: "+tempPath+Thread.currentThread().getStackTrace()[2].getLineNumber());
	    // Parse the request
	    List<FileItem> items = null;
	    try 
	    {
	    	items = upload.parseRequest(request);
		} catch (FileUploadException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // Process the uploaded items
	    Iterator<FileItem> iter = items.iterator();
	    String JsonString = null;
	//    FileItem fileItem = null;
	    int maxtkid = 0;
//	    response.setContentType("text/html");
	    while (iter.hasNext()) 
	    {
	        FileItem item = iter.next();
	/*            String device_id = null;
	        String idcard = null;
	        String gate = null;
	        String time = null;
	        String accessstat = null;
	        String entrance = null; 
	        int maxtkid = 0;   */           
	        if (item.isFormField())                                        // Process a regular form field
	        {            	
	       	    String name = item.getFieldName();
	            String value = item.getString("UTF-8");
	//            System.out.println("form.field.name = " + name + "   value = " + value);
	             if ("JsonString".equals(name)) 
	            {
	                JsonString = value;
	            }
	            JSONObject jsonO = null;
	            try 
	    		{
	    			jsonO = new JSONObject(JsonString);
	    		} catch (JSONException e) 
	    		{
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	//    		JSONObject jsonO;
	//    		jsonO = (JSONObject)jsonTokener.nextValue(); 
	            try 
	            {
	//    			System.out.println("device_id : " + jsonO.getString("device_id"));
	            	String device_id = jsonO.getString("device_id");
	            	String idcard = jsonO.getString("idcard");
	            	String gate = jsonO.getString("gate");
	            	String time = jsonO.getString("time");
	            	String accessstat = jsonO.getString("accessstat");
	            	String entrance = jsonO.getString("entrance");
	//    			System.out.println("device_id : " + device_id+" idcard : " + idcard+" gate : " + 
	//    				gate+" time : " + time+" accessstat : " + accessstat+" entrance : " + entrance);
	    			if(gate.isEmpty()||device_id.isEmpty()||time.isEmpty()||idcard.isEmpty())
	    			{
	    				response.setContentType("text/html");
	    				PrintWriter out = response.getWriter();
	    				out.println("{\"result\":\"ERROR\"}");
	    				out.flush();
	    				out.close();
	    				System.out.println("{\"result\":\"ERROR\"}");
	    				return;
	    			}
	    			if(accessstat.isEmpty())
	    			{
	    				accessstat="pass";
	    			}
	    			if(entrance.isEmpty())
	    			{
	    				entrance="in";
	    			}
	    			
	    			SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMddkkmmss");
	    		    SimpleDateFormat sf2 =new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
	    		    String sfstr = "";
	    		    sfstr = sf2.format(sf1.parse(time));
	    		    
	    			String content = null;
	    			try 
	        		{
	        			Class.forName("com.mysql.jdbc.Driver");
	        		} catch (ClassNotFoundException e) 
	        		{
	        			System.out.println("com.mysql.jdbc.Driver Exception,109");
	        			response.setContentType("text/html");
	    				PrintWriter out = response.getWriter();
	    				out.println("{\"result\":\"ERROR\"}");
	    				out.flush();
	    				out.close();
	    				System.out.println("{\"result\":\"ERROR\"}");
	    				return;
	        		}
	        		//����Connection����
	        		Connection conn = null;
	        		try 
	        		{
	        			//1.getConnection()����������MySQL��ݿ�
	        			conn = DriverManager.getConnection(URL, NAME, PASSWORD);
	        		} catch (SQLException e) 
	        		{
	        			// TODO Auto-generated catch block
	//        						e.printStackTrace();
	        			System.out.println("DriverManager.getConnection Exception,120");
	        			response.setContentType("text/html");
	    				PrintWriter out = response.getWriter();
	    				out.println("{\"result\":\"ERROR\"}");
	    				out.flush();
	    				out.close();
	    				System.out.println("{\"result\":\"ERROR\"}");
	    				return;
	        		}
	        		//2.����statement���������ִ��SQL���
	        		Statement stmt = null;
	        		try 
	        		{
	        			stmt = conn.createStatement();
	        		} catch (SQLException e) 
	        		{
	        			// TODO Auto-generated catch block
	//        						e.printStackTrace();
	        			if(conn!=null)
						try 
	        			{
							conn.close();
						} catch (SQLException e1) 
						{
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
	        			System.out.println("conn.createStatement Exception,132");
	        			response.setContentType("text/html");
	    				PrintWriter out = response.getWriter();
	    				out.println("{\"result\":\"ERROR\"}");
	    				out.flush();
	    				out.close();
	    				System.out.println("{\"result\":\"ERROR\"}");
	    				return;
	        		}
	        		content="INSERT INTO accessrecord(controlerNum,cardnum,gatenum,CreatedTime,accessstat," +
	        			"entrance) VALUES('"+device_id+"','"+idcard+"','"+gate+"','"+sfstr+"','"+
	        			accessstat+"','"+entrance+"');";
	//        		System.out.println(content);
	    			try 
	    			{
						int udresult  = stmt.executeUpdate(content);
					} catch (SQLException e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    			Statement stmt1 = null;
	        		try 
	        		{
	        			stmt1 = conn.createStatement();
	        		} catch (SQLException e) 
	        		{
	        			// TODO Auto-generated catch block
	//        						e.printStackTrace();
	        			System.out.println("conn.createStatement Exception,132");
	        		}
	        		content="SELECT MAX(tkid) FROM accessrecord WHERE controlerNum = '"+device_id+
	        				"' AND cardnum='"+idcard+"' AND gatenum='"+gate+"' AND CreatedTime='"+sfstr+"';";
	//        		System.out.println(content);
	        		ResultSet rs = null;
	        		try 
	    			{
	        			rs = stmt.executeQuery(content);
	        			while(rs.next())
	        			{
	        				maxtkid = rs.getInt(1);
	        			}
	        			rs.close();
	        			System.out.println("maxtkid = "+maxtkid);
					} catch (SQLException e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	    			// �ر���Դ
	                try
	                {
	                    if(stmt!=null) stmt.close();
	                    if(stmt1!=null) stmt1.close();
	                }catch(SQLException se2)
	                {
	                }// ʲô������
	                try
	                {
	                    if(conn!=null) conn.close();
	                }catch(SQLException se)
	                {
	                    se.printStackTrace();
	                }            		
	    		} catch (JSONException e) 
	    		{
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        } else                                                         // Process a file upload
	        {
	//            String name = item.getFieldName();
	//            String filename = item.getName();
	//        	System.out.println("maxtkid_363 = "+maxtkid);
	            int flen = (int) item.getSize();
	//            System.out.println(" file.length = " + flen);
	            if (flen >= 0) 
	            {
	//                fileItem = item;
	//                String filePath = "/code/server/java/dwserver/dw/WebRoot/pics";
	            	String filePath = "D:/apache-tomcat-7/webapps/dw/pics";
	                String filename = maxtkid+".jpg";
	                File uploadFile = new File(filePath + "/" + filename); 
	//                System.out.println("uploadFile_342 = "+filePath + "/" + filename);
	                try 
	                {
						item.write(uploadFile);
	//   					System.out.println("uploadFile_346 = "+filePath + "/" + filename);
					} catch (Exception e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	            
	        }
	    }
	//    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
	
	//    sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
	//    byte[] bt = null;
	//    bt = decoder.decodeBuffer(content);
	//    content=new String(bt);
	//    System.out.println("out.dwrealtime..... "+Thread.currentThread().getStackTrace()[2].getLineNumber());
	    
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("{\"result\":\"OK\"}");
		out.flush();
		out.close();
	}
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
